//
//  AddSideViewController.m
//  fitnessmanage
//
//  Created by wujian on 2017/10/29.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//

#import "AddSideViewController.h"
#import "AddSideTableViewCell.h"
#import "AddSideView.h"

@interface AddSideViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UIButton *addBtn;

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,strong)NSMutableDictionary *dict;

//保存自定义添加的数据（数组保存 名称，单位）
@property(nonatomic,strong)NSMutableArray *unitDataArray;

@end

@implementation AddSideViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"添加体测模板";
    
    self.view.backgroundColor = BackGroundColor;
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateHighlighted];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    [self createSubView];
    
    if (self.sideDict) {
        
        NSString *fieldItems = [self.sideDict objectForKey:@"FieldItems"];
        
        NSMutableArray *array = [NSMutableArray arrayWithArray:[fieldItems JSONValue]];
        
        for (NSDictionary *dict in array) {
            
            NSString *name = [dict objectForKey:@"Name"];
            
            NSString *unit = [dict objectForKey:@"Unit"];
            
            //页面显示
            [self.dict setObject:unit forKey:name];
            
            [self.dataSource addObject:name];
        }
        
        NSIndexPath *nameIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        NSIndexPath *memoIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        
        AddSideTableViewCell *nameCell = [self.tableView cellForRowAtIndexPath:nameIndexPath];
        
        AddSideTableViewCell *memocell = [self.tableView cellForRowAtIndexPath:memoIndexPath];
        
        nameCell.nameInputView.titleTF.text = [self.sideDict objectForKey:@"Name"];
        
        memocell.nameInputView.titleTF.text = [self.sideDict objectForKey:@"Desc"];
        
        [self.tableView reloadData];
    }
    
}

-(void)createSubView{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 100;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerClass:[AddSideTableViewCell class] forCellReuseIdentifier:@"AddSideTableViewCell"];
    [tableView registerClass:[AddSideTableViewCellCustom class] forCellReuseIdentifier:@"AddSideTableViewCellCustom"];
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    self.tableView = tableView;
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = CSWhiteColor;
    if (self.sideDict){
        
        bottomView.frame = CGRectMake(0, 0, self.view.width, 120);
    }
    else{
        
        bottomView.frame = CGRectMake(0, 0, self.view.width, 60);
    }
    
    UIButton *addBtn = [[UIButton alloc] init];
    [addBtn setTitle:@"添加 +"];
    [addBtn setTitleColor:TFColor];
    addBtn.titleLabel.font = MidBigFont;
    addBtn.backgroundColor = BackGroundColor;
    addBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
    [addBtn addTarget:self action:@selector(addSideContent)];
    [bottomView addSubview:addBtn];
    self.addBtn = addBtn;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = MidBigFont;
    titleLabel.textColor = CSColorFromRGB(0x666666);
    titleLabel.text = @"体侧内容";
    [bottomView addSubview:titleLabel];
    [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.addBtn);
        make.left.mas_equalTo(bottomView).offset(10);
    }];
    
    
    [addBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(bottomView).offset(10);
        make.left.mas_equalTo(titleLabel.mas_right).offset(20);
    }];
    
    if (self.sideDict){
     
        UIButton *deleteBtn = [[UIButton alloc] init];
        deleteBtn.frame = CGRectMake(0, 0, self.view.width, 50);
        [deleteBtn setTitle:@"删除"];
        [deleteBtn addTarget:self action:@selector(delBtnClick)];
        deleteBtn.titleLabel.font = MidBigFont;
        [deleteBtn setTitleColor:CSColorFromRGB(0xff464e)];
        deleteBtn.backgroundColor = CSWhiteColor;
        [bottomView addSubview:deleteBtn];
        
        [deleteBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(addBtn.mas_bottom).offset(10);
            
            make.left.width.bottom.mas_equalTo(bottomView);
            
            make.height.mas_equalTo(50);
        }];
    }
    
    tableView.tableFooterView = bottomView;
}

#pragma mark UITableViewDataSourc
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row < 2) {
        
        AddSideTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddSideTableViewCell"];
        
        NSString *title = [self.dataSource objectAtIndex:indexPath.row];
        
        cell.nameInputView.titleLabel.text = title;
        
        cell.nameInputView.titleTF.placeholder = [NSString stringWithFormat:@"请输入%@",title];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    else{
        
        AddSideTableViewCellCustom *cell = [tableView dequeueReusableCellWithIdentifier:@"AddSideTableViewCellCustom"];
        
        NSString *text = [self.dataSource objectAtIndex:indexPath.row];
        
        //名称
        cell.titleLabel.text = text;
        
        NSString *unit = [self.dict objectForKey:text];
        
        //单位
        cell.unitLabel.text = unit;
        
        if (indexPath.row == 2) {
            
            cell.upBtn.enabled = NO;
        }
        else{
         
            cell.upBtn.enabled = YES;
        }
        
        cell.upBtn.tag = indexPath.row;
        cell.clearBtn.tag = indexPath.row;
        
        [cell.upBtn addTarget:self action:@selector(upBtnClick:)];        
        [cell.clearBtn addTarget:self action:@selector(delBtnClick:)];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
}

#pragma mark UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.00001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}

#pragma mark 上移
-(void)upBtnClick:(UIButton *)btn{
    
    NSInteger tag = btn.tag;
    
    NSInteger topTag = tag - 1;
    
    [self.dataSource exchangeObjectAtIndex:tag withObjectAtIndex:topTag];
    
    [self.tableView reloadData];
}

#pragma mark 删除
-(void)delBtnClick:(UIButton *)btn{
    
    NSInteger tag = btn.tag;
    
    NSString *name = [self.dataSource objectAtIndex:tag];
    
    [self.dataSource removeObjectAtIndex:tag];
    
    [self.dict removeObjectForKey:name];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
}

#pragma mark 添加体侧内容
-(void)addSideContent{
    
    AddSideView *addSideView = [[AddSideView alloc] init];
    
    addSideView.dict = self.dict;
    
    __weak __typeof(self) weakSelf = self;
    
    addSideView.commitBlock = ^(NSString *name, NSString *unit) {

        //页面显示
        [weakSelf.dict setObject:unit forKey:name];
        
        [weakSelf.dataSource addObject:name];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:weakSelf.dataSource.count - 1 inSection:0];
        
        //表格插入新的一行
        [weakSelf.tableView beginUpdates];
        
        [weakSelf.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
        
        [weakSelf.tableView endUpdates];
    };
    
    [addSideView showWithAnimation];
}

#pragma mark 右侧按钮点击
-(void)rightBtnClick{
    
    NSIndexPath *nameIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    NSIndexPath *memoIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    
    AddSideTableViewCell *nameCell = [self.tableView cellForRowAtIndexPath:nameIndexPath];
    
    AddSideTableViewCell *memocell = [self.tableView cellForRowAtIndexPath:memoIndexPath];
    
    NSString *sideName = nameCell.nameInputView.titleTF.text;
    
    NSString *memo = memocell.nameInputView.titleTF.text;
    
    if (!sideName) {
        
        [MBProgressHUD showText:@"请输入模板名字"];
        
        return;
    }
    
    //传递服务器保存数据
    [self.unitDataArray removeAllObjects];
    
    for (int i = 2; i < self.dataSource.count; i++) {
    
        NSString *name = [self.dataSource objectAtIndex:i];
        
        NSString *unit = [self.dict objectForKey:name];
        
        NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] init];
        
        [dataDict setObject:name forKey:@"Name"];
        
        [dataDict setObject:unit forKey:@"Unit"];
        
        [self.unitDataArray addObject:dataDict];
    }
    
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:sideName forKey:@"Name"];
    
    [params setObject:memo forKey:@"Desc"];
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
    
    [params setObject:[userDefault objectForKey:@"UserID"] forKey:@"AddUserID"];
    
    [params setObject:[self.unitDataArray toJSONString] forKey:@"FieldItems"];
    
    [params setValue:[self.sideDict objectForKey:@"ID"] forKey:@"ID"];
    
    [HTTPTool POSTRaw:Post_BodyData_Operate parameters:params
     
              success:^(id responseObject){
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                      
                      [MBProgressHUD showText:@"操作成功"];
                      
                      [NotificationCenter postNotificationName:@"ReloadSide" object:nil];
                      
                      [self.navigationController popViewControllerAnimated:YES];
                  }
                  
              }
     
              failure:^(NSError *error){
                  
                  [MBProgressHUD hideHUDForView:self.view];
              }];
}

#pragma mark 删除按钮点击
-(void)delBtnClick{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"message:@"确定删除?"preferredStyle:UIAlertControllerStyleAlert];
    
    //添加取消到UIAlertController中
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alertController addAction:cancelAction];
    
    //添加确定到UIAlertController中
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //Post_Shop_DeleteShop
        [MBProgressHUD showMessage:@"删除中..." toView:self.view];
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        
         NSString *delUrl = [NSString stringWithFormat:@"%@/%@",Post_DelBodyData,[self.sideDict objectForKey:@"ID"]];
        
        //[params setObject:[self.sideDict objectForKey:@"ID"] forKey:@"ID"];
        
        [HTTPTool POSTRaw:delUrl parameters:params success:^(id responseObject) {
            
            [MBProgressHUD hideHUDForView:self.view];
            
            if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){
                
                [MBProgressHUD showText:@"删除成功"];
                
                [NotificationCenter postNotificationName:@"ReloadSide" object:nil];
                
                [self.navigationController popViewControllerAnimated:YES];
            }
            else{
                
                [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
            }
            
        } failure:^(NSError *error) {
            
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showText:@"删除失败"];
        }];
        
    }];
    
    [alertController addAction:OKAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark Get

-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
        
        [_dataSource addObject:@"模板名称"];
        
        [_dataSource addObject:@"描述内容"];
    }
    
    return _dataSource;
}


-(NSMutableDictionary *)dict{
    
    if (!_dict) {
        
        _dict = [[NSMutableDictionary alloc] init];
    }
    
    return _dict;
}

-(NSMutableArray *)unitDataArray{
    
    if (!_unitDataArray) {
        
        _unitDataArray = [[NSMutableArray alloc] init];
    }
    
    return _unitDataArray;
}
@end
